/*
 * settings_manager.cpp
 * 串口调试工具 - 设置管理模块源文件
 * 
 * 此文件包含SettingsManager类的实现，负责应用设置的保存、加载和管理功能。
 */

#include "settings_manager.h"
#include <QDebug>

// 构造函数实现
SettingsManager::SettingsManager(const QString &organization, const QString &application, QObject *parent)
    : QObject(parent)
{
    // 初始化设置对象
    settings = new QSettings(organization, application, this);
    
    // 初始化默认设置
    initializeDefaults();
}

// 析构函数实现
SettingsManager::~SettingsManager()
{
    // 清理资源
    delete settings;
}

// 初始化默认设置
void SettingsManager::initializeDefaults()
{
    // 初始化默认串口参数
    defaultBaudRate = 115200;
    defaultDataBits = "8";
    defaultStopBits = "1";
    defaultParity = "None";
    defaultFlowControl = "None";
    
    // 初始化其他默认值
    recentPortHistory.clear();
    portConfigs.clear();
    windowGeometry.clear();
    windowState.clear();
    uiOptions.clear();
}

// 加载应用设置
void SettingsManager::loadSettings()
{
    // 加载最近连接的串口历史
    settings->beginGroup("recentPorts");
    recentPortHistory = settings->value("history", QStringList()).toStringList();
    settings->endGroup();
    
    // 加载串口配置
    settings->beginGroup("portConfigs");
    QStringList portKeys = settings->childKeys();
    for (const QString &portName : portKeys) {
        QString configStr = settings->value(portName).toString();
        QMap<QString, QString> config;
        
        // 解析配置字符串格式: "baud:115200;dataBits:8;stopBits:1;parity:None;flowControl:None"
        QStringList parts = configStr.split(';');
        for (const QString &part : parts) {
            int colonIndex = part.indexOf(':');
            if (colonIndex != -1) {
                QString key = part.left(colonIndex);
                QString value = part.mid(colonIndex + 1);
                config[key] = value;
            }
        }
        
        portConfigs[portName] = config;
    }
    settings->endGroup();
    
    // 加载窗口状态
    settings->beginGroup("window");
    windowGeometry = settings->value("geometry").toByteArray();
    windowState = settings->value("state").toByteArray();
    settings->endGroup();
    
    // 加载UI选项
    settings->beginGroup("uiOptions");
    QStringList optionKeys = settings->childKeys();
    for (const QString &key : optionKeys) {
        uiOptions[key] = settings->value(key);
    }
    settings->endGroup();
    
    // 加载默认串口参数
    settings->beginGroup("defaultParameters");
    defaultBaudRate = settings->value("baudRate", 115200).toInt();
    defaultDataBits = settings->value("dataBits", "8").toString();
    defaultStopBits = settings->value("stopBits", "1").toString();
    defaultParity = settings->value("parity", "None").toString();
    defaultFlowControl = settings->value("flowControl", "None").toString();
    settings->endGroup();
    
    qDebug() << "Settings loaded successfully";
}

// 保存应用设置
void SettingsManager::saveSettings()
{
    // 保存最近连接的串口历史
    settings->beginGroup("recentPorts");
    settings->setValue("history", recentPortHistory);
    settings->endGroup();
    
    // 保存串口配置
    settings->beginGroup("portConfigs");
    // 先清除现有配置
    QStringList portKeys = settings->childKeys();
    for (const QString &key : portKeys) {
        settings->remove(key);
    }
    // 保存新配置
    for (auto it = portConfigs.constBegin(); it != portConfigs.constEnd(); ++it) {
        const QString &portName = it.key();
        const QMap<QString, QString> &config = it.value();
        
        // 构建配置字符串格式: "baud:115200;dataBits:8;stopBits:1;parity:None;flowControl:None"
        QStringList configParts;
        for (auto configIt = config.constBegin(); configIt != config.constEnd(); ++configIt) {
            configParts << configIt.key() + ":" + configIt.value();
        }
        
        settings->setValue(portName, configParts.join(";"));
    }
    settings->endGroup();
    
    // 保存窗口状态
    settings->beginGroup("window");
    settings->setValue("geometry", windowGeometry);
    settings->setValue("state", windowState);
    settings->endGroup();
    
    // 保存UI选项
    settings->beginGroup("uiOptions");
    for (auto it = uiOptions.constBegin(); it != uiOptions.constEnd(); ++it) {
        settings->setValue(it.key(), it.value());
    }
    settings->endGroup();
    
    // 保存默认串口参数
    settings->beginGroup("defaultParameters");
    settings->setValue("baudRate", defaultBaudRate);
    settings->setValue("dataBits", defaultDataBits);
    settings->setValue("stopBits", defaultStopBits);
    settings->setValue("parity", defaultParity);
    settings->setValue("flowControl", defaultFlowControl);
    settings->endGroup();
    
    // 确保写入磁盘
    settings->sync();
    
    qDebug() << "Settings saved successfully";
}

// 设置最近连接的串口历史
void SettingsManager::setRecentPortHistory(const QStringList &history)
{
    recentPortHistory = history;
}

// 获取最近连接的串口历史
QStringList SettingsManager::getRecentPortHistory() const
{
    return recentPortHistory;
}

// 添加串口到最近连接历史
void SettingsManager::addToRecentPortHistory(const QString &portName, int maxItems)
{
    // 如果端口已在历史中，先移除
    recentPortHistory.removeAll(portName);
    // 添加到历史列表的最前面
    recentPortHistory.prepend(portName);
    // 限制历史记录数量
    if (recentPortHistory.size() > maxItems) {
        recentPortHistory = recentPortHistory.mid(0, maxItems);
    }
}

void SettingsManager::addToPortHistory(const QString &portName)
{
    // 默认最多保留10条最近端口历史
    addToRecentPortHistory(portName, 10);
}

// 设置串口参数配置
void SettingsManager::setPortConfig(const QString &portName, const QMap<QString, QString> &config)
{
    portConfigs[portName] = config;
}

// 获取串口参数配置
QMap<QString, QString> SettingsManager::getPortConfig(const QString &portName) const
{
    if (portConfigs.contains(portName)) {
        return portConfigs[portName];
    }
    
    // 如果没有找到配置，返回默认配置
    QMap<QString, QString> defaultConfig;
    defaultConfig["baud"] = QString::number(defaultBaudRate);
    defaultConfig["dataBits"] = defaultDataBits;
    defaultConfig["stopBits"] = defaultStopBits;
    defaultConfig["parity"] = defaultParity;
    defaultConfig["flowControl"] = defaultFlowControl;
    
    return defaultConfig;
}

// 设置窗口状态
void SettingsManager::setWindowState(const QByteArray &geometry, const QByteArray &state)
{
    windowGeometry = geometry;
    windowState = state;
}

// 获取窗口几何信息
QByteArray SettingsManager::getWindowGeometry() const
{
    return windowGeometry;
}

// 获取窗口状态
QByteArray SettingsManager::getWindowState() const
{
    return windowState;
}

// 设置UI选项
void SettingsManager::setUiOption(const QString &optionName, const QVariant &value)
{
    uiOptions[optionName] = value;
}

// 获取UI选项
QVariant SettingsManager::getUiOption(const QString &optionName, const QVariant &defaultValue) const
{
    if (uiOptions.contains(optionName)) {
        return uiOptions[optionName];
    }
    return defaultValue;
}

// 设置默认串口参数
void SettingsManager::setDefaultPortParameters(int baudRate, const QString &dataBits,
                                             const QString &stopBits, const QString &parity,
                                             const QString &flowControl)
{
    defaultBaudRate = baudRate;
    defaultDataBits = dataBits;
    defaultStopBits = stopBits;
    defaultParity = parity;
    defaultFlowControl = flowControl;
}

// 获取默认波特率
int SettingsManager::getDefaultBaudRate() const
{
    return defaultBaudRate;
}

// 获取默认数据位
QString SettingsManager::getDefaultDataBits() const
{
    return defaultDataBits;
}

// 获取默认停止位
QString SettingsManager::getDefaultStopBits() const
{
    return defaultStopBits;
}

// 获取默认校验位
QString SettingsManager::getDefaultParity() const
{
    return defaultParity;
}

// 获取默认流控制
QString SettingsManager::getDefaultFlowControl() const
{
    return defaultFlowControl;
}

// 清除所有设置
void SettingsManager::clearAllSettings()
{
    settings->clear();
    initializeDefaults();
    qDebug() << "All settings cleared";
}